package com.cxs.distributedgamedemo.slice;

import com.cxs.distributedgamedemo.ResourceTable;
import com.cxs.distributedgamedemo.util.KvStoreUtils;
import com.cxs.distributedgamedemo.util.UIUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Text;
import ohos.data.distributed.common.ChangeNotification;
import ohos.data.distributed.common.KvStoreObserver;
import ohos.data.distributed.common.SubscribeType;
import ohos.data.distributed.user.SingleKvStore;

public class GameUIAbilitySlice extends AbilitySlice {
    SingleKvStore kvStore = null;
    Text text;
    // 实现KvStoreObserver接口，用于订阅数据库变化，也可单独创建一个类实现接口
    private class KvStoreObserverClient implements KvStoreObserver {
        @Override
        public void onChange(ChangeNotification changeNotification) {
            System.out.println("=================================");
            String action = kvStore.getString("action");
            getUITaskDispatcher().delayDispatch(() -> {
                text.append("\n点击了 " + action);
            }, 0);

            System.out.println("=================================");

        }
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_game_ui);

        text = (Text)findComponentById(ResourceTable.Id_text_game_info);
        kvStore = KvStoreUtils.getKvStore(this);

        // 构造并注册KvStoreObserver实例用于订阅数据库变化
        KvStoreObserverClient kvStoreObserverClient = new KvStoreObserverClient();
        kvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_ALL, kvStoreObserverClient);


    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
